package controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"mytest/code"
	"mytest/database"
	"mytest/flower-order/model"
	"mytest/util"
	"time"
)

type HuashuCategoryController struct {
}

func (h *HuashuCategoryController) Index(c *gin.Context) {
	var huashuCategoryList []*model.HuashuCategory
	var formHelper util.FormHelper
	params := [][]string{
		{"page", "int", "num|has"},
		{"limit", "int", "num|has"},
		{"searchParams", "string-no-filter"},
	}

	paramMap, err := formHelper.Params(params, c)
	if err != nil {
		c.JSON(code.Success, util.ReturnError(code.ParamErr, err.Error()))
		return
	}
	conditions := " 1=1 "
	if len(paramMap["searchParams"].(string)) > 0 {
		searchParams := make(map[string]string)
		err = json.Unmarshal([]byte(paramMap["searchParams"].(string)), &searchParams)
		if err != nil {
			c.JSON(code.Success, util.ReturnError(code.ParamErr, err.Error()))
			return
		}
		for k, v := range searchParams {
			if v == "" {
				continue
			}
			if k == "name" {
				conditions += fmt.Sprintf(" and `name` like  '%%%s%%' ", v)
			} else {
				conditions += fmt.Sprintf(" and `%s` =  '%s' ", k, v)
			}
		}
	}

	limit := paramMap["limit"].(int)
	page := paramMap["page"].(int)
	offset := (page - 1) * limit
	var count int64
	database.DB.Debug().Model(model.HuashuCategory{}).Select("id").Where(conditions).Count(&count)
	err = database.DB.Debug().Model(model.HuashuCategory{}).
		Select("*,datetime(created_at) as created_at,datetime(updated_at) as updated_at,datetime(deleted_at) as deleted_at").
		Where(conditions).
		Limit(limit).Offset(offset).
		Order("sort desc").
		Order("id desc").
		Find(&huashuCategoryList).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		c.JSON(code.Success, util.ReturnError(code.SysErr, err.Error()))
		return
	}
	response := util.ReturnSuccess(huashuCategoryList)
	response["count"] = count
	c.JSON(code.Success, response)
	return
}

func (h *HuashuCategoryController) Show(c *gin.Context) {
	var huashuCategory model.HuashuCategory
	var formHelper util.FormHelper
	params := [][]string{
		{"id", "string", "required|num"},
	}
	paramMap, err := formHelper.Params(params, c)
	if err != nil {
		c.JSON(code.Success, err.Error())
		return
	}
	err = database.DB.Debug().Model(model.HuashuCategory{}).
		Where("id = ?", paramMap["id"]).
		First(&huashuCategory).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		c.JSON(code.Success, util.ReturnError(code.SysErr, err.Error()))
		return
	}
	c.JSON(code.Success, util.ReturnSuccess(huashuCategory))
	return
}

func (h *HuashuCategoryController) Add(c *gin.Context) {
	var huashuCategory model.HuashuCategory
	err := c.BindJSON(&huashuCategory)
	if err != nil {
		c.JSON(code.Success, util.ReturnError(code.ParamErr, err.Error()))
		return
	}
	nowTimeStr := time.Now().Local().Format(util.TimeLayout)
	huashuCategory.CreatedAt = nowTimeStr
	huashuCategory.UpdatedAt = nowTimeStr
	err = database.DB.Debug().Model(model.HuashuCategory{}).Create(&huashuCategory).Error
	if err != nil {
		c.JSON(code.Success, util.ReturnError(code.SysErr, err.Error()))
		return
	}
	c.JSON(code.Success, util.ReturnSuccess(nil))
	return
}

func (h *HuashuCategoryController) Edit(c *gin.Context) {
	var dataMap map[string]interface{}
	err := c.BindJSON(&dataMap)
	if err != nil {
		c.JSON(code.Success, util.ReturnError(code.ParamErr, err.Error()))
		return
	}
	dataMap["updated_at"] = time.Now().Local().Format(util.TimeLayout)
	id := int(dataMap["id"].(float64))
	delete(dataMap, "id")
	delete(dataMap, "deleted_at")
	delete(dataMap, "created_at")
	err = database.DB.Debug().Model(&model.HuashuCategory{Id: id}).Updates(dataMap).Error
	if err != nil {
		c.JSON(code.Success, util.ReturnError(code.SysErr, err.Error()))
		return
	}
	c.JSON(code.Success, util.ReturnSuccess(nil))
	return
}
